package com.ksy.common.login;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;

import com.ksy.common.utils.Constants;
import com.ksy.common.utils.LogTool;
import com.ksy.common.wxapi.WXEntryActivity;
import com.tencent.mm.opensdk.openapi.IWXAPI;
import com.tencent.mm.opensdk.openapi.WXAPIFactory;

/**
 * Created by ksy on 2018/3/27.
 */

public class WeChatPlatform implements LoginPlatform<WeChatInfo> {
    private final Context context;
    private IWXAPI api;
    private Listener listener;

    public  interface Listener {
        void onSuccess(WeChatInfo weChatInfo);

        void onError(String msg);

        void onCancel();
    }
    public WeChatPlatform(Context context) {
        this.context = context;
    }

    @Override
    public boolean isCanLogin() {
        if (api == null) {
            api = WXAPIFactory.createWXAPI(context, Constants.WeChatID, true);
            api.registerApp(Constants.WeChatID);
        }
        return api.isWXAppInstalled();
    }

    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (Login_Code_WeChat_Success == resultCode) {
            //登录成功
            WeChatInfo weChatInfo = data.getParcelableExtra("weChatInfo");
            onSuccess(weChatInfo);
        } else if (Login_Code_WeChat_Cancel == resultCode) {
            //登录取消
            onCancel();
        } else if (Login_Code_WeChat_Error == resultCode) {
            //登录失败
            onError("微信授权失败");
        }
    }

    public void loginTo(Activity activity, Listener listener) {
        this.listener=listener;
        Intent intent = new Intent(activity, WXEntryActivity.class);
        intent.putExtra("isHand", true);
        activity.startActivityForResult(intent, 996);
        activity.overridePendingTransition(0, 0);
    }

    @Override
    public void onSuccess(WeChatInfo weChatInfo) {
        LogTool.e("WeChatInfo  onSuccess     " + weChatInfo);
        if (listener != null) {
            listener.onSuccess(weChatInfo);
        }
    }

    @Override
    public void onError(String msg) {
        LogTool.e("WeChatInfo  onError   " + msg);
        if (listener != null) {
            listener.onError(msg);
        }
    }

    @Override
    public void onCancel() {
        LogTool.e("WeChatInfo  onCancel   ");
        if (listener != null) {
            listener.onCancel();
        }
    }


}
